$(document).ready(function () {

	InitBinding();
});



function InitBinding() {

	//On submit on add page, submit the add and shows the success
	//page it the edit was successful, otherwise add page is shown again including
	//validation errors
    $("#EditSubmit").click(function (e) {


        e.preventDefault();
        CallPostRequestForEditConfirmSnippet();
    });


	$('#FoundCategories').change(function () {
		$('#NewCodeCategoryName').val($("#FoundCategories option:selected").text());
	});

	$('#SearchForExistingCategories').click(function (e) {
	    e.preventDefault();
	    var categoryName = $('#SearchCategoryText').val();
	    DoLookupSearch(categoryName, 'category', 'TryFindCategory',
            { categoryName: categoryName },
            '#FoundCategories',
            SetCategoriesArea,
		    function (input) { return input.CodeCategoryName; },
		    function (input) { return input.CodeCategoryId; },
		    function (input) { return input.CodeCategoryName; },
		    function () { SetCategoriesArea(false, undefined, 'Couldn\'t find any matching categories'); },
		    function () { SetCategoriesArea(false, undefined, data.Message) });
	});


    $('#FoundGrouping').change(function () {
		$('#NewGroupingName').val($("#FoundGrouping option:selected").text());
	});


    $('#SearchForExistingGrouping').click(function (e) {
	    e.preventDefault();
	    var groupName = $('#SearchGroupingText').val();
	    DoLookupSearch(groupName, 'grouping', 'TryFindGrouping',
            { groupName: groupName },
            '#FoundGrouping',
            SetGroupingArea,
		    function (input) { return input.Description; },
		    function (input) { return input.GroupId; },
		    function (input) { return input.Description; },
		    function () { SetGroupingArea(false, undefined, 'Couldn\'t find any matching grouping'); },
		    function () { SetGroupingArea(false, undefined, data.Message) });
	});

}








function DoLookupSearch(searchElementValue, searchingForText, ajaxMethod, map, foundElementName, 
areaFunc, foundSelector1, foundSelector2, foundSelector3, errorfunc1, errorfunc2) {

	if (searchElementValue == undefined || searchElementValue == '') {
		showOkDialog('You didn\'t enter a ' + searchingForText + ' to search for', 180, 'Error');
	}
	else {
	    $.post("/CodeSnippet/" + ajaxMethod, map,
				function (data) {
				    if (data.Success != undefined && data.Success) {
				        if (data.Message.length > 0) {
                            areaFunc(true, foundSelector1(data.Message[0]), '');
				            populateSelect(foundElementName, data.Message,
								foundSelector2,
								foundSelector3);
				            $(foundElementName).show();
				        }
				        else {
				            errorfunc1();
				        }
				    }
				    else {
				        errorfunc2();
				    }
				},
				"json");
	}
}


function SetCategoriesArea(valid, value, message) {

 	if (valid) {
		$('#NewCodeCategoryName').val(value);
	}
	else {
		$('#NewCodeCategoryName').val('');
		$('#FoundCategories').hide();
		showOkDialog(message, 180, 'Error');
	}
}


function SetGroupingArea(valid, value, message) {

 	if (valid) {
		$('#NewGroupingName').val(value);
	}
	else {
		$('#NewGroupingName').val('');
		$('#FoundGrouping').hide();
		showOkDialog(message, 180, 'Error');
	}
}

//Ajax request to load in next page of results
function CallPostRequestForEditConfirmSnippet() {

	var formData = $("#EditForm").serialize();

	$.post("/CodeSnippet/Edit", formData, function (response) {
	    $("#AjaxEditContents").replaceWith(response);
	    InitBinding();

	    var successfulAdd = $('#successfulEdit').val();
	    if (successfulAdd == "True") {
	        var addedSnippetId = $('#editedSnippetId').val();
	        window.location.href = '/CodeSnippet/DisplaySnippetsForAddAndEdit' + '?codeSnippetId=' + addedSnippetId;
	    }
	    else {
	        showOkDialog('Could not update your code snippet', 180, 'Error');
	    }
	});
	return false;
}
